package services

import (
	"strconv"

	"github.com/mlogclub/simple/sqls"
	"github.com/mlogclub/simple/web/params"
	"gorm.io/gorm"

	"bbs-go/internal/models"
	"bbs-go/internal/pkg/config"
	"bbs-go/internal/repositories"
)

var IndexArticleService = newIndexArticleService()

func newIndexArticleService() *indexArticleService {
	return &indexArticleService{}
}

type indexArticleService struct {
}

func (s *indexArticleService) Get(id int64) *models.IndexArticle {
	return repositories.IndexArticleRepository.Get(sqls.DB(), id)
}

func (s *indexArticleService) Take(where ...interface{}) *models.IndexArticle {
	return repositories.IndexArticleRepository.Take(sqls.DB(), where...)
}

func (s *indexArticleService) Find(cnd *sqls.Cnd) []models.IndexArticle {
	return repositories.IndexArticleRepository.Find(sqls.DB(), cnd)
}

func (s *indexArticleService) FindPageByParams(params *params.QueryParams) (list []models.IndexArticle, paging *sqls.Paging) {
	return repositories.IndexArticleRepository.FindPageByParams(sqls.DB(), params)
}

func (s *indexArticleService) FindPageByCnd(cnd *sqls.Cnd) (list []models.IndexArticle, paging *sqls.Paging) {
	return repositories.IndexArticleRepository.FindPageByCnd(sqls.DB(), cnd)
}

func (s *indexArticleService) Create(t *models.IndexArticle) error {
	return repositories.IndexArticleRepository.Create(sqls.DB(), t)
}

func (s *indexArticleService) Update(t *models.IndexArticle) error {
	return repositories.IndexArticleRepository.Update(sqls.DB(), t)
}

func (s *indexArticleService) Updates(id int64, columns map[string]interface{}) error {
	return repositories.IndexArticleRepository.Updates(sqls.DB(), id, columns)
}

func (s *indexArticleService) UpdateColumn(id int64, name string, value interface{}) error {
	return repositories.IndexArticleRepository.UpdateColumn(sqls.DB(), id, name, value)
}

func (s *indexArticleService) Delete(id int64) error {
	return repositories.IndexArticleRepository.Delete(sqls.DB(), id)
}

func (s *indexArticleService) FindSimpleList(page *models.IndexArticleSimpleRequest) (resp models.IndexArticleSimpleResponse, err error) {
	limit := page.Limit
	offset := page.Limit * (page.Page - 1)
	if limit == 0 {
		limit = 10
	}
	db := sqls.DB()

	querySql := `select ia.id,ia.created_at,ia.index_category_id,ia.title,ia.summary,ia.cover,ia.source,ia.source_url 
	from index_article ia 
	where 1=1 and ia.deleted_at is null  `
	whereSql := ""
	whereVars := []interface{}{}

	whereSql += " and ia.index_category_id = ? "
	whereVars = append(whereVars, page.IndexCategoryId)

	if page.IndexShow > 0 {
		whereSql += " and ia.index_show = ? "
		whereVars = append(whereVars, page.IndexShow)
	}

	countSql := `select count(1)
	from index_article ia 
	where 1=1 `

	var total int64
	err = db.Raw(countSql+whereSql, whereVars...).Scan(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return models.IndexArticleSimpleResponse{}, err
	}

	list := []models.IndexArticleSimple{}
	orderBySql := " order by ia.index_show desc,ia.sort desc,ia.id desc LIMIT " + strconv.Itoa(limit) + " OFFSET " + strconv.Itoa(offset)
	err = db.Raw(querySql+whereSql+orderBySql, whereVars...).Find(&list).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return models.IndexArticleSimpleResponse{}, err
	}

	resList := []models.IndexArticleSimpleDto{}
	for _, v := range list {
		resList = append(resList, models.IndexArticleSimpleDto{
			Id:              v.Id,
			CreatedAt:       v.CreatedAt.Format("2006-01-02 15:04:05"),
			IndexCategoryId: v.IndexCategoryId,
			Title:           v.Title,
			Summary:         v.Summary,
			Cover:           v.Cover,
			Sort:            v.Sort,
			Source:          v.Source,
			SourceUrl:       v.SourceUrl,
			IndexShow:       v.IndexShow,
		})
	}
	indexArticleSimpleResponse := models.IndexArticleSimpleResponse{
		List: resList,
		Paging: &sqls.Paging{
			Page:  page.Page,
			Limit: page.Limit,
			Total: total,
		},
	}
	indexCategoryInfo := IndexCategoryService.Get(int64(page.IndexCategoryId))
	if indexCategoryInfo != nil {
		indexArticleSimpleResponse.IndexCategoryName = indexCategoryInfo.Name
	}

	return indexArticleSimpleResponse, nil
}

func (s *indexArticleService) FindIndexContent() (resp models.IndexContentResponse, err error) {
	// 热门话题
	list1, err := s.FindSimpleList(&models.IndexArticleSimpleRequest{
		Limit:           10,
		Page:            1,
		IndexCategoryId: 11, // 热门话题
		IndexShow:       0,
	})
	if err != nil {
		return models.IndexContentResponse{}, err
	}
	resp.IndexInfo1 = models.IndexInfo{
		IndexTitle: list1.IndexCategoryName,
		IndexList:  list1.List,
	}

	list2, err := s.FindSimpleList(&models.IndexArticleSimpleRequest{
		Limit:           8,
		Page:            1,
		IndexCategoryId: 9, // 技术保障
		IndexShow:       0,
	})
	if err != nil {
		return models.IndexContentResponse{}, err
	}
	resp.IndexInfo2 = models.IndexInfo{
		IndexTitle: list2.IndexCategoryName,
		IndexList:  list2.List,
	}

	list3, err := s.FindSimpleList(&models.IndexArticleSimpleRequest{
		Limit:           8,
		Page:            1,
		IndexCategoryId: 5, // 装备生产
		IndexShow:       0,
	})
	if err != nil {
		return models.IndexContentResponse{}, err
	}
	resp.IndexInfo3 = models.IndexInfo{
		IndexTitle: list3.IndexCategoryName,
		IndexList:  list3.List,
	}

	// 宣传视频

	return resp, nil
}

func (s *indexArticleService) FindIndexContentV2() (resp models.IndexContentV2Response, err error) {
	//论坛地址
	resp.BBSUrl = config.Instance.BBSUrl
	//资讯动态
	newsTrends, err := s.FindSimpleList(&models.IndexArticleSimpleRequest{
		Limit:           10,
		Page:            1,
		IndexCategoryId: 11, // 资讯动态
		IndexShow:       0,
	})
	if err != nil {
		return models.IndexContentV2Response{}, err
	}
	resp.NewsTrends = models.IndexInfo{
		IndexTitle: newsTrends.IndexCategoryName,
		IndexList:  newsTrends.List,
	}

	// 系统公告
	systemNoticeList, err := SystemNoticeService.FindShowIndexList()
	if err != nil {
		return resp, err
	}

	systemNoticeDtoList := []models.SystemNoticeDto{}
	for _, systemNotice := range systemNoticeList {
		systemNoticeDtoList = append(systemNoticeDtoList, models.SystemNoticeDto{
			Id:        systemNotice.Id,
			CreatedAt: systemNotice.CreatedAt.Format("2006-01-02 15:04:05"),
			Title:     systemNotice.Title,
			Summary:   systemNotice.Summary,
		})
	}

	resp.SystemNotice = models.SystemNoticeInfo{
		Title: "系统公告",
		List:  systemNoticeDtoList,
	}

	bbsTypes := []models.BBSType{}
	// 交流论坛
	topicNodes := TopicNodeService.GetNodesIndex()
	for _, topicNode := range topicNodes {
		bbsTypes = append(bbsTypes, models.BBSType{
			Id:   int(topicNode.Id),
			Name: topicNode.Name,
		})
	}

	bbsTypes = append(bbsTypes, models.BBSType{
		Id:   999,
		Name: "更多",
		Url:  config.Instance.BBSUrl,
	})

	resp.BBSInfo = models.BBSInfo{
		Title:    "交流论坛",
		BBSTypes: bbsTypes,
	}

	// // 精彩贴图
	// imageList := []models.ExcitingTexture{}

	// imageList = append(imageList, models.ExcitingTexture{
	// 	Name:     "精彩贴图1",
	// 	ImageUrl: "http://www.81.cn/lj_208555/jdt_208556/_attachment/2024/08/29/16334168_81cd1e16149a927690ce70c53d010ff5_0+0_640*360.jpg",
	// })
	// imageList = append(imageList, models.ExcitingTexture{
	// 	Name:     "精彩贴图2",
	// 	ImageUrl: "http://www.81.cn/lj_208555/jdt_208556/_attachment/2024/08/22/16332902_daa63e1037789e5456bc934f55b6dc36_0+0_640*360.jpg",
	// })
	// imageList = append(imageList, models.ExcitingTexture{
	// 	Name:     "精彩贴图3",
	// 	ImageUrl: "http://www.81.cn/tp_207717/_attachment/2024/07/24/16326586_17b479051aee7a05795fe7dc348e50c3.jpg",
	// })
	// imageList = append(imageList, models.ExcitingTexture{
	// 	Name:     "精彩贴图4",
	// 	ImageUrl: "http://www.81.cn/tp_207717/_attachment/2024/08/01/16328840_4cd60cc8cb94df62149d2fc63c3da3fb.jpg",
	// })
	// imageList = append(imageList, models.ExcitingTexture{
	// 	Name:     "精彩贴图5",
	// 	ImageUrl: "http://www.81.cn/tp_207717/_attachment/2024/07/19/16325605_bf2d7fde60b21395d44940cb5386360f.jpg",
	// })
	// 精彩贴图
	excitingTexture, err := s.FindSimpleList(&models.IndexArticleSimpleRequest{
		Limit:           4,
		Page:            1,
		IndexCategoryId: 13, // 精彩贴图
		IndexShow:       0,
	})
	if err != nil {
		return models.IndexContentV2Response{}, err
	}
	resp.ExcitingTexture = models.IndexInfo{
		IndexTitle: excitingTexture.IndexCategoryName,
		IndexList:  excitingTexture.List,
	}

	// resp.ExcitingTexture = models.ExcitingTextureInfo{
	// 	Title: "精彩贴图",
	// 	List:  imageList,
	// }
	return resp, nil
}
